<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use app\common\library\Express;
use app\common\model\Express as ModelExpress;
use app\common\model\goods\Spec;
use app\common\model\MoneyLog;
use app\common\model\Order as ModelOrder;
use app\common\model\order\Goods;
use app\common\model\order\goods\Log;
use app\common\model\order\Order as OrderOrder;
use app\common\model\User;
use app\common\model\user\Info;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\order\Order;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("expressComList", ModelExpress::all());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("settleList", $this->model->getSettleList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user', 'goods'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username', 'nickname']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 发货
     */
    public function deliver($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $post = request()->post("row/a");
            extract($post);
            if (!isset($ids) || empty($ids)) {
                $this->error('参数错误');
            }
            if (!isset($express_no) || empty($express_no)) {
                $this->error('物流编号不能为空');
            }
            if (!isset($express_com) || empty($express_com)) {
                $this->error('物流公司不能为空');
            }
            $data = [
                'order_status' => '20',
                'sendtime' => time(),
                'express_com' => $express_com,
                'express_no' => $express_no,
            ];
            $order = $this->model->get($ids);
            if (!$order) {
                $this->error('订单不存在');
            }
            if (!in_array($order->order_status, ['10', '20'])) {
                $this->error('订单状态错误');
            }
            $res = $order->allowField(true)->save($data);
            if (!$res) {
                $this->error('发货失败');
            }
            $this->success('发货成功');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    /**
     * 查询物流
     */
    public function query()
    {
        $get = $this->request->param();
        $kd = new Express($get);
        $wuliu = $kd->getOrderTracesByJson();
        $this->assign('data', isset($wuliu['status']) && $wuliu['status'] == 200 && count((array) $wuliu['data']) ? (array) $wuliu['data'] : $wuliu['message'] ?? '');
        return $this->view->fetch();
    }
    /**
     * 审核
     */
    public function examine($ids = null)
    {
        if ($this->request->isPost()) {
            $post = request()->post("row/a");
            extract($post);
            if (!isset($ids) || empty($ids)) {
                $this->error('参数错误');
            }
            $order = $this->model->get($ids, ['goods']);
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order->examine != '10') {
                $this->error('审核状态错误');
            }

            $order->examine = $examine;
            Db::startTrans();
            try {
                $time = time();
                if ($examine == '20') {
                    $order->order_status = '10';
                    $order->paytime = $time;
                    MoneyLog::frozenlog_commission($order);
                    Log::add_performance_detail($order, $time);
                } else {
                    $order->order_status = $examine;
                    foreach ($order->goods as $k => $v) {
                        Spec::stockUp($v['goods_id'], $v['spec_id'], $v['goods_num']);
                    }
                }
                $res = $order->allowField(true)->save();
                if ($res && $order->order_type == '2'&& $examine == '20') {
                    $expiration_date = config('site.expiration_date');
                    $goods = $order->goods;
                    $arr = [
                        'user_id' => $order->user_id,
                        'group_id' => 2,
                        'province' => $order->province,
                        'city' => $order->city,
                        'area' => $order->area,
                        'address' => $order->regio,
                        'content' => json_encode($order),
                        'first_cate' => $goods[0]['first_cate'],
                        'two_cate' => $goods[0]['two_cate'],
                        'region_id' => $goods[0]['region_id'],
                        'expirationtime' => strtotime("+" . $expiration_date . " day"),
                    ];
                    if ($order->renewal == 1) {
                        $expiration = $expiration_date * 86400;
                        $data = Info::get(['first_cate' => $goods[0]['first_cate'], 'two_cate' => $goods[0]['two_cate'], 'address' => $order->regio, 'user_id' => $order->user_id]);
                        if ($data) {
                            $data->expirationtime = bcadd($data->expirationtime ?? $time, $expiration, 0);
                            $data->save();
                        } else {
                            Info::create($arr, true);
                        }
                    } else {
                        Info::create($arr, true);
                    }
                    User::where('id', $order->user_id)->update(['group_id' => 2]);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('审核成功');
        }
        return $this->view->fetch();
    }

    /**
     * 个人业绩
     */
    public function performance()
    {
        //当前是否为关联查询
        $this->model = new Log();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $uid = $this->request->get('uid', 0);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //我的个人消费金额
            $idss = ModelOrder::where('order_status', '>', '0')->where('user_id', $uid)->column('id');
            $list =  Goods::with(['order'])->whereIn('order_id', $idss)->where($where)->order($sort, $order)->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 直推业绩
     */
    public function direct_thrust_performance()
    {
        //当前是否为关联查询
        $this->model = new Log();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $uid = $this->request->get('uid', 0);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //我的直推消费金额
            $uids = User::where('pid', $uid)->column('id');
            $idss = ModelOrder::where('order_status', '>', '0')->whereIn('user_id', $uids)->column('id');
            $list =  Goods::with(['order'])->whereIn('order_id', $idss)->where($where)->order($sort, $order)->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 团队业绩
     */
    public function team_performance()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->model = new Log();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $first_cate = $this->request->get('first_cate', 0);
            $two_cate = $this->request->get('two_cate', 0);
            $uid = $this->request->get('uid', 0);
            $info = Info::where(['user_id' => $uid, 'first_cate' => $first_cate, 'two_cate' => $two_cate])->where('shareholder|investment', '>', 3)->find();
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);
            $wheres['p_shareholder'] = ['>', 3];
            if (!isset($filter['is_settle'])) {
                $filter['is_settle'] = 0;
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = Log::with(['order', 'goods'])->where('log.user_id', $info->user_id ?? 0)->where($where)->where($wheres)->where(['log.first_cate' => $first_cate, 'log.two_cate' => $two_cate])->order($sort, $order)->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function series_performance()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->model = new Log();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $first_cate = $this->request->get('first_cate', 0);
            $two_cate = $this->request->get('two_cate', 0);
            $uid = $this->request->get('uid', 0);
            $info = Info::where(['user_id' => $uid, 'first_cate' => $first_cate, 'two_cate' => $two_cate])->where('shareholder|investment', '>', 3)->find();
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);
            $wheres['p_investment'] = ['=', 6];

            if (!isset($filter['is_settle'])) {
                $filter['is_settle'] = '0';
                $op['is_settle'] = '=';
            }
            if ($filter['is_settle'] == '0') {
                if (!isset($filter['createtime']) && !isset($filter['settletime']) && $info) {
                    if ($info->settlementtime > 0) {
                        $wheres['log.createtime'] = ['>', $info->settlementtime];
                    }
                }
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = Log::with(['order', 'goods'])->where('log.user_id', $info->user_id ?? 0)->where($where)->where($wheres)->where(['log.first_cate' => $first_cate, 'log.two_cate' => $two_cate])->paginate();
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
}
